<template>
	<div class="change-password">
		<nav-bar title="修改密码" :custom-back="true" @on-back="handleBack" />
		<!-- 密码输入区域 -->
		<van-cell-group>
			<van-field v-model="oldPsd" label="旧密码" placeholder="请输入旧密码" :maxlength="11" class="password-input" />

			<van-field v-model="newPsd" label="新密码" placeholder="请输入新密码" :maxlength="11" class="password-input" />

			<van-field v-model="newAgainPsd" label="确认密码" placeholder="请再次输入新密码" :maxlength="11"
				class="password-input" />
		</van-cell-group>

		<div class="tip">提示：请包含大小写字母和数字,且长度不小于8位。</div>

		<van-button type="primary" block class="submit-btn" @click="submitClick">
			保存
		</van-button>
	</div>
</template>

<script>
	import NavBar from '@/components/NavBar'
	import {
		doUpdatePassword
	} from "@/api/changePassword.js"
	import {
		Toast
	} from 'vant';
	export default {
		name: 'ChangePassword',
		components: {
			NavBar
		},
		data() {
			return {
				oldPsd: '',
				newPsd: '',
				newAgainPsd: '',
				user: []
			}
		},
		created() {
			this.user = JSON.parse(localStorage.getItem('user'))
		},
		methods: {
			handleBack() {
				this.$router.push('/mine')
			},
			async submitClick() {

				let that = this;
				var myreg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
				let isRight = myreg.test(that.newPsd);
				if (!isRight) {
					Toast.success("新密码请包含大小写字母和数字,且长度不小于8位");
					return;
				}
				if (that.newPsd != that.newAgainPsd) {
					Toast.success("两次密码不一致，请重新输入");
					return;
				}
				try {
					doUpdatePassword({
							openSessionId: this.user.openSessionId,
							oldPwd: this.oldPsd,
							newPwd: this.newPsd,
						})
						.then(res => {
							if (res.code == 200) {
								Toast.success("密码修改成功");
								setTimeout(function() {
									that.$router.push('/mine')
								}, 1000);
							} else {
								Toast.fail(res.message);
							}
						})
				} catch (err) {
					Toast.fail('密码修改失败')
				} finally {
					this.isLoading = false
				}


			}
		}
	}
</script>

<style lang="scss" scoped>
	.change-password {
		margin-top: 44px;
		min-height: 100vh;
		background: #f5f5f5;
		padding: 12px 15px;

		.password-input {
			margin-bottom: 5px;
			background: #fff;
			border-radius: 6px;

			::v-deep .van-cell__title {
				flex: none;
				width: 75px;
			}
		}

		.tip {
			color: #999;
			font-size: 12px;
			margin-top: 10px;
		}

		.submit-btn {
			margin-top: 20px;
			color: #fff;
			background-color: #1989fa;
			border: 1px solid #1989fa;
		}

		:deep(.van-button) {}
	}
</style>